/*
Copyright 2021 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Package tmpdir provides helper getting a temporary directory for tests that
// write to the filesystem.
package tmpdir

import (
	"os"
	"testing"
)

// New creates and returns a path to a temporary directory and registers a
// cleanup function to delete the directory on test completion.
//
// The new directory's name is generated by adding a random string to the end of
// pattern and follows os.MkdirTemp semantics.
func New(t *testing.T, dir, pattern string) string {
	t.Helper()
	tmpDir, err := os.MkdirTemp(dir, pattern)
	if err != nil {
		t.Fatalf("expected err to be nil, got: %+v", err)
	}
	t.Cleanup(func() {
		if err := os.RemoveAll(tmpDir); err != nil {
			t.Fatalf("error cleaning up tmp dir: %s", err)
		}
	})
	return tmpDir
}
